package com.winai.launcher.view.set;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.ks.projectbasictools.retrofit.HttpResponseListener;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.CommonBean;
import com.winai.launcher.bean.responseEntity.DialModelEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.ScreenProtectConstant;
import com.winai.launcher.manager.ScreenProtectManager;
import com.winai.launcher.override.CheckableTextView;
import com.winai.launcher.override.CountTimer;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.PicassoLoadUtils;
import com.winai.launcher.utils.MathUtils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.ServerUtils;
import com.winai.launcher.view.ScreenProtectActivity;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;

import static com.winai.launcher.constant.HttpUrls.DIAL_MODEL;

/**
 * 作者：康少
 * 时间：2019/11/27
 * 说明：屏幕设置
 */
public class SetLightActivity extends BaseActivity {
    private Context mContext = this;

    @BindView(R.id.tv_empty)
    TextView tvEmpty;
    @BindView(R.id.seek_light)
    SeekBar seekLight;
    @BindView(R.id.str_title)
    TextView strTitle;
    @BindView(R.id.tfl_list)
    TagFlowLayout tflList;//自动进入屏保时间
    @BindView(R.id.tfl_list2)
    TagFlowLayout tflList2;//表盘模式
    @BindView(R.id.cl)
    ConstraintLayout cl;

    /*变量*/
//    private CommonBean selectTimeBean;//选中的时间对象
//    private ScreenSaveEntity.DataBean.ScreenSaverVoListBean selectScreenProtectBean;//选中的屏保对象
    private List<CommonBean> beanList = new ArrayList<>();//时间数据集合
    private List<DialModelEntity.DataBean> screenProtectBeanList = new ArrayList<>();//屏保数据集合
    private TagAdapter<CommonBean> timeAdapter;//时间adapter
    private TagAdapter<DialModelEntity.DataBean> screenProtectAdapter;//屏保adapter
    private int lightNum = 0;//亮度
//    private int progress = 0;

    private boolean isLoaded = false;
    private NetworkListener mNetworkStateReceiver;
    private ContentObserver brightnessMode;//监听亮度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_light);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        addData();
        initListener();
    }

    @SuppressLint("SetTextI18n")
    private void initObject() {
        String titleName = getIntent().getStringExtra("titleName");
        strTitle.setText(titleName);

        brightnessMode = new ContentObserver(new Handler()) {
            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                //更新亮度值UI
                updateSystemBrightness();
            }
        };

        requestSettingsPermission();//申请设置权限

        updateSystemBrightness();
    }

    private void addData() {
        /*设置屏保时间*/
//        beanList.add(new CommonBean(ScreenProtectConstant.time == ScreenProtectConstant.HALF ? "1" : "0", "30秒后"));
        beanList.add(new CommonBean(ScreenProtectConstant.time == ScreenProtectConstant.TWENTY ? "1" : "0", "20分钟后"));
        beanList.add(new CommonBean(ScreenProtectConstant.time == ScreenProtectConstant.THIRTY ? "1" : "0", "30分钟后"));
        beanList.add(new CommonBean(ScreenProtectConstant.time == ScreenProtectConstant.SIXTY ? "1" : "0", "1小时后"));
//        beanList.add(new CommonBean(ScreenProtectConstant.time == ScreenProtectConstant.TEN ? "1" : "0", "10分钟后"));
        beanList.add(new CommonBean(ScreenProtectConstant.time == ScreenProtectConstant.NEVER ? "1" : "0", "永不"));
        initSleepView();
        /*设置屏保壁纸*/
        requestScreenSaveList();
    }

    private void requestScreenSaveList() {
        if (!canIn()) {
            return;
        }
        ServerUtils.requestJsonPost(DIAL_MODEL, null, new Object(), new HttpResponseListener<DialModelEntity>() {
            @Override
            public void onResponse(DialModelEntity bean, boolean isCache) {
                showEmpty(bean.getData().size() == 0);
                screenProtectBeanList.clear();
                for (DialModelEntity.DataBean bb : bean.getData()) {
                    bb.setChecked(false);
                    switch (bb.getType()) {
                        case "0":
                            bb.setPictureName("屏保");
                            break;
                        case "1":
                            bb.setPictureName("动态画报");
                            break;
                        case "2":
                            bb.setPictureName("无屏保");
                            break;
                    }
                    screenProtectBeanList.add(bb);
                }
                initScreenSave();
                showScreenProtectCheck();
            }

            @Override
            public void onError(int code, String msg) {
                super.onError(code, msg);
                showEmpty(true);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable e) {
                super.onFailure(call, e);
                showEmpty(true);
            }
        });
    }

    private long sTime = 0;//请求的时间
    private boolean canIn() {
        //再次请求时间
        long ct = System.currentTimeMillis();
        if (ct - sTime < 2000) {
            LogUtils.d("2s内限制屏保接口请求");
            return false;
        }
        sTime = ct;
        return true;
    }

    private void showEmpty(boolean showEmpty) {
        isLoaded = !showEmpty;
        tvEmpty.setVisibility(showEmpty ? View.VISIBLE : View.GONE);
    }

    /*设置屏保时间*/
    private void initSleepView() {
        timeAdapter = new TagAdapter<CommonBean>(beanList) {
            @Override
            public View getView(FlowLayout parent, int position, CommonBean o) {
                CheckableTextView view = (CheckableTextView) LayoutInflater.from(mContext).inflate(R.layout.item_set_light_time, parent, false);
                view.setText(o.getStr());
                view.setChecked(o.getId().equals("1"));
                return view;
            }
        };
//        if (selectTimeBean != null && Integer.parseInt(selectTimeBean.getId()) >= 1) {
//            timeAdapter.setSelectedList(Integer.parseInt(selectTimeBean.getId()) - 1);
//        }
        tflList.setAdapter(timeAdapter);
        tflList.setOnSelectListener(selectPosSet -> {
            String selectIndex = selectPosSet.toString();
            LogUtils.d("选中的进入屏保时间：" + selectIndex);
            setScreenProtectTime(selectIndex);
        });
    }

    /*设置屏保壁纸*/
    private void initScreenSave() {
        screenProtectAdapter = new TagAdapter<DialModelEntity.DataBean>(screenProtectBeanList) {
            @Override
            public View getView(FlowLayout parent, int position, DialModelEntity.DataBean o) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.item_set_light_protect, parent, false);
                if (!TextUtils.isEmpty(o.getPicturePath())) {
                    PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(o.getPicturePath(), view.findViewById(R.id.iv_image));
                }
                view.findViewById(R.id.iv_checked).setVisibility(o.isChecked() ? View.VISIBLE : View.GONE);
                ((TextView) view.findViewById(R.id.tv_pickerName)).setText(o.getPictureName());
                return view;
            }
        };
//        if (selectScreenProtectBean != null && Integer.parseInt(selectScreenProtectBean.getId()) >= 1) {
//            screenProtectAdapter.setSelectedList(Integer.parseInt(selectScreenProtectBean.getId()) - 1);
//        }
        tflList2.setAdapter(screenProtectAdapter);
        tflList2.setOnTagClickListener((view, position, parent) -> {
            LogUtils.d("选中的屏保：" + position);
            //预览屏保
            previewScreenProtect(position);
            return false;
        });
    }

    private void initListener() {
        seekLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                SetLightActivity.this.progress = progress;
                //取得window属性保存在layoutParams中
                WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
                layoutParams.screenBrightness = (float) MathUtils.divide(progress, 255, 2);
                getWindow().setAttributes(layoutParams);
                //显示修改后的亮度
                layoutParams = getWindow().getAttributes();
                lightNum = (int) (layoutParams.screenBrightness * 100);
                //修改系统的亮度值,以至于退出应用程序亮度保持
                saveBrightness(getContentResolver(), progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
        mContext.getContentResolver().registerContentObserver(
                Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS)
                , true
                , brightnessMode);
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.CHANGE_SCREENPROTECT:
                        //设置屏保选中
                        updateScreenProtectCheck();
                        break;
                }
            }
        });

        //注册网络监听广播 
        mNetworkStateReceiver = new NetworkListener();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mNetworkStateReceiver, filter);
    }

    /**
     * 说明：更新亮度值
     */
    private void updateSystemBrightness() {
        //接收到系统亮度改变
        int systemBrightness = getSystemBrightness();
        seekLight.setProgress(systemBrightness);
    }

    private void requestSettingsPermission() {
        //系统设置权限
        if (!Settings.System.canWrite(mContext)) {
            ToastKs.show(mContext, "请打开此权限");
            Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
            intent.setData(Uri.parse("package:" + mContext.getPackageName()));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(intent);
        }
    }

    public static void saveBrightness(ContentResolver resolver, int brightness) {
        //改变系统的亮度值(申请权限失败)
        //这里需要权限android.permission.WRITE_SETTINGS
        //设置为手动调节模式
        Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS_MODE,
                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
        //保存到系统中
        Uri uri = Settings.System.getUriFor(Settings.System.SCREEN_BRIGHTNESS);
        Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightness);
        resolver.notifyChange(uri, null);
    }

    /**
     * 说明：设置进入屏保时间
     */
    private void setScreenProtectTime(String selectIndex) {
        DB_Common db_common = new DB_Common(mContext);
        switch (selectIndex) {
            case "[0]":
                if(validate()) return;
                ScreenProtectConstant.time = ScreenProtectConstant.TWENTY;
                //重启计时器
                CountTimer.restart(mContext);
                for (CommonBean bean : beanList) {
                    bean.setId("0");
                }
                beanList.get(0).setId("1");
                timeAdapter.notifyDataChanged();
                break;
            case "[1]":
                if(validate()) return;
                ScreenProtectConstant.time = ScreenProtectConstant.THIRTY;
                //重启计时器
                CountTimer.restart(mContext);
                for (CommonBean bean : beanList) {
                    bean.setId("0");
                }
                beanList.get(1).setId("1");
                timeAdapter.notifyDataChanged();
                break;
            case "[2]":
                if(validate()) return;
                ScreenProtectConstant.time = ScreenProtectConstant.SIXTY;
                //重启计时器
                CountTimer.restart(mContext);
                for (CommonBean bean : beanList) {
                    bean.setId("0");
                }
                beanList.get(2).setId("1");
                timeAdapter.notifyDataChanged();
                break;
//            case "[3]":
//                if(validate()) return;
//                ScreenProtectConstant.time = ScreenProtectConstant.TEN;
//                //重启计时器
//                CountTimer.restart(mContext);
//                for (CommonBean bean : beanList) {
//                    bean.setId("0");
//                }
//                beanList.get(3).setId("1");
//                timeAdapter.notifyDataChanged();
//                break;
            case "[3]":
                ScreenProtectConstant.time = ScreenProtectConstant.NEVER;
                //取消定时器
                CountTimer.release();
                for (CommonBean bean : beanList) {
                    bean.setId("0");
                }
                beanList.get(3).setId("1");
                timeAdapter.notifyDataChanged();
                break;

        }
        db_common.add(ScreenProtectConstant.TIME, ScreenProtectConstant.time + "");
    }

    /**
     * @date 4/19/21
     * @desc 屏保模式是否为"无屏保"，true：是；false：否
     */
    private boolean validate() {
        return ScreenProtectManager.getModel() == ScreenProtectManager.ScreenProtectModel.NULL;
    }

    /**
     * 说明：预览屏保
     */
    private void previewScreenProtect(int selectIndex) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("fromSetCenter", "true");
        Intent ScreenProtectIntent = new Intent(mContext, ScreenProtectActivity.class);
        ScreenProtectIntent.putExtra("fromSetCenter", "true");
        DialModelEntity.DataBean dataBean = screenProtectBeanList.get(selectIndex);
        switch (dataBean.getType()) {
            case "0":
                //静态预览
                ScreenProtectManager.setYuModel(ScreenProtectManager.ScreenProtectModel.STATIC);
//                startAct(mContext, ScreenProtectActivity.class, map);
                startActivity(ScreenProtectIntent);
                break;
            case "1":
                //动态预览
                ScreenProtectManager.setYuModel(ScreenProtectManager.ScreenProtectModel.DYNAMIC);
//                startAct(mContext, ScreenProtectActivity.class, map);
                startActivity(ScreenProtectIntent);
                break;
            case "2":
                //无屏保
                ScreenProtectManager.setYuModel(ScreenProtectManager.ScreenProtectModel.NULL);
                updateScreenProtectCheck();
                //设置屏保时间为"永不"
                setScreenProtectTime("[3]");
                break;
        }
    }

    /**
     * 说明：更新屏幕保护选中
     */
    private void updateScreenProtectCheck() {
        DB_Common db_common = new DB_Common(mContext);
        for (int i = 0; i < screenProtectBeanList.size(); i++) {
            screenProtectBeanList.get(i).setChecked(false);
        }
        if (ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.STATIC) {
            ScreenProtectManager.setModel(ScreenProtectManager.ScreenProtectModel.STATIC);
            screenProtectBeanList.get(0).setChecked(true);
            db_common.add(ScreenProtectConstant.MODEL, "static");
        } else if (ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.DYNAMIC) {
            ScreenProtectManager.setModel(ScreenProtectManager.ScreenProtectModel.DYNAMIC);
            screenProtectBeanList.get(1).setChecked(true);
            db_common.add(ScreenProtectConstant.MODEL, "dynamic");
        } else if (ScreenProtectManager.getYuModel() == ScreenProtectManager.ScreenProtectModel.NULL) {
            ScreenProtectManager.setModel(ScreenProtectManager.ScreenProtectModel.NULL);
            screenProtectBeanList.get(2).setChecked(true);
            db_common.add(ScreenProtectConstant.MODEL, "null");
        }
        screenProtectAdapter.notifyDataChanged();
    }

    /**
     * @date 2020/8/27
     * @desc 展示屏保选中项
     */
    private void showScreenProtectCheck() {
        for (int i = 0; i < screenProtectBeanList.size(); i++) {
            screenProtectBeanList.get(i).setChecked(false);
        }
        switch (ScreenProtectManager.getModel()) {
            case STATIC:
                screenProtectBeanList.get(0).setChecked(true);
                break;
            case DYNAMIC:
                screenProtectBeanList.get(1).setChecked(true);
                break;
            case NULL:
                screenProtectBeanList.get(2).setChecked(true);
                break;
        }
        screenProtectAdapter.notifyDataChanged();
    }

    /**
     * 说明：获取系统亮度
     */
    private int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    /**
     * 作者：康少
     * 时间：2020/3/18 0018
     * 说明：网络监听
     */
    public class NetworkListener extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (NetworkUtils.hasNetwork(context) && !isLoaded) {
                requestScreenSaveList();
            }
        }
    }

    public static void setAutoAdjustBrightness(Context context, boolean auto) {
        int value = 0;
        if (auto) {
            value = Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
        } else {
            value = Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL;
        }
        ContentResolver cr = context.getContentResolver();
        Settings.System.putInt(cr, Settings.System.SCREEN_BRIGHTNESS_MODE, value);
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.iv_light})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.iv_light:
//                setAutoAdjustBrightness(mContext, true);
                //更新亮度值UI
                setSystemBrightness();
                break;
        }
    }

    private void setSystemBrightness() {
        int light = 40;
        float screenBrightness = (float) MathUtils.divide(light, 100, 2);
        float progress = screenBrightness * 255;
        seekLight.setProgress((int) progress);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetworkStateReceiver != null) {
            try {
                unregisterReceiver(mNetworkStateReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                //LogUtils.e("捕捉一个crash：Receiver not registered");
            }
        }
        mContext.getContentResolver().unregisterContentObserver(brightnessMode);
    }
}
